package com.cgc.venus.server.core.exception;

import com.cgc.venus.server.core.bean.response.VenusExceptionResponse;
import com.cgc.venus.server.core.bean.response.VenusResponseStatus;
import com.cgc.venus.server.core.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 全局异常处理
 * Created by 业哥 on 2017/6/6.
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 平台业务异常处理
     * @param req
     * @param ex
     * @return
     */
    @ExceptionHandler(VenusException.class)
    @ResponseBody
    public VenusExceptionResponse handleCmpServiceException(HttpServletRequest req, Exception ex) {
        logger.error(ex.getMessage(),ex);
        VenusException cmpException= (VenusException) ex;
        int code=cmpException.getCode();
        insertEsLog(req,"业务异常",code,ex.getMessage());
        return VenusExceptionResponse.create(VenusResponseStatus.VENUS_EXCEPTION, ex.getMessage());
    }

    /**
     * 平台系统异常处理比如：404,500
     * @param req
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public VenusExceptionResponse handleCmpException(HttpServletRequest req, Exception ex) {
        logger.error(ex.getMessage(),ex);
        Integer code= VenusResponseStatus.INTERNAL_SERVER_ERROR;
        if (ex instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            code=VenusResponseStatus.NOT_FOUND;
        }else if(ex instanceof org.springframework.web.HttpRequestMethodNotSupportedException){
            code=VenusResponseStatus.METHOD_NOT_ALLOWED;
        }
        insertEsLog(req,"系统异常",code,ex.getMessage());
        String rmsg="系统异常:"+code+",请联系管理员!";
        return VenusExceptionResponse.create(VenusResponseStatus.SYSTEM_EXCEPTION,rmsg);
    }

    /**
     *
     */
    private void insertEsLog(HttpServletRequest request,String type,int code,String msg){
        try {
            String token=request.getHeader("X-Token");
            String userId="";
            if(!StringUtil.isEmpty(token)){
                String sql="select id from t_user where token='"+token+"'";
                List<Map<String, Object>> r2=jdbcTemplate.queryForList(sql);
                if(r2!=null&&r2.size()>0){
                    userId=r2.get(0).get("id").toString();
                }
            }
            String sql = "INSERT INTO t_ex_log(id,user,type,code,msg,Create_time) VALUES (?,?,?,?,?,NOW())";
            List<Object> objs = new ArrayList<Object>();
            objs.add(StringUtil.getUUID());
            objs.add(userId);
            objs.add(type);
            objs.add(code);
            objs.add(msg);
            jdbcTemplate.update(sql, objs.toArray());
        }catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }
    }
}